import React, {Component} from 'react'
import {connect} from 'react-redux'
import actions from '../action'
import {FlatList} from 'react-native'
import Toast from 'react-native-easy-toast'
import {
    createMaterialTopTabNavigator,
    createAppContainer,
} from 'react-navigation'
import {
    DeviceInfo,
    View,
    StyleSheet,
    RefreshControl,
} from 'react-native'
import PopularItem from '../common/PopularItem'
import TrendingItem from '../common/TrendingItem'
import NavigationBar from '../common/NavigationBar'
import navigatorUtil from "../navigator/navigatorUtil";
import FavoriteDao from '../expand/dao/FavoriteDao'
import FavoriteUtil from '../util/FavoriteUtil'
import {FLAG_STORAGE} from '../expand/dao/DataStore'
import EventBus from 'react-native-event-bus'
import EventTypes from '../util/EventTypes'

const THEME_COLOR = 'red'
// const flag = FLAG_STORAGE.flag_popular
// const favoriteDao = new FavoriteDao(flag)

export default class FavoritePage extends Component {
    constructor(props) {
        super(props)
    }


    _genTabs() {
        const {theme} = this.props
        return {
            'Popular': {
                screen: props => <FavoriteTabPage {...props} theme={theme} flag={FLAG_STORAGE.flag_popular}/>,
                navigationOptions: {
                    title: '最热',
                }
            },
            'Trending': {
                screen: props => <FavoriteTabPage {...props} theme={theme} flag={FLAG_STORAGE.flag_trending}/>,
                navigationOptions: {
                    title: '趋势',
                }
            }
        }
    }

    render() {
        let statusBar = {
            backgroundColor: '#678',
            barStyle: 'light-content',
            hidden: false,
        }
        const navigationBar = <NavigationBar
            title={'收藏'}
            statusBar={statusBar}
            style={{backgroundColor: "#678"}}
        />
        const TabNavigator = createAppContainer(createMaterialTopTabNavigator(
            this._genTabs(),
            {
                tabBarOptions: {
                    tabStyle: styles.tabStyle,
                    upperCaseLabel: false, //是否标签大写
                    // scrollEnabled: true, //是否支持 选项卡滚动，默认False
                    style: {
                        backgroundColor: '#678',
                    },
                    indicatorStyle: styles.indicatorStyle,
                    labelStyle: styles.labelStyle,
                }
            }
        ))
        return (
            <View style={{flex: 1, marginTop: DeviceInfo.isIPhoneX_deprecated ? 30 : 0}}>
                {navigationBar}
                <TabNavigator/>
            </View>
        )

    }

}

class FavoriteTab extends Component {
    constructor(props) {
        super(props);
        const {flag} = this.props
        this.storeName = flag

    }

    componentDidMount() {
        this.loadData()
        EventBus.getInstance().addListener(EventTypes.BOTTOM_NAV_CHANGE, this.listenNavChange = data => {
            if (data.to === 2) {
                this.loadData(false)
            }
        })
    }
    componentWillUnmount(){
        EventBus.getInstance().removeListener(this.listenNavChange)
    }

    loadData(isLoading) {
        const {onLoadFavorite} = this.props
        onLoadFavorite(this.storeName, isLoading)
    }


    renderItem(data) {
        const {item} = data
        const Item = this.storeName === FLAG_STORAGE.flag_popular ? PopularItem : TrendingItem
        let favoriteDao = new FavoriteDao(this.storeName)
        return <Item
            projectModel={item}
            theme={this.props.theme}
            onSelect={(callback) => {
                navigatorUtil.goPage({
                    projectModel: item,
                    flag: this.storeName,
                    callback,
                }, 'DetailPage')
            }}
            onFavorite={(item, isFavorite) => FavoriteUtil.onFavorite(favoriteDao, item, isFavorite, this.storeName)}
        />
    }


    render() {
        const {favorite} = this.props
        let store = favorite[this.storeName]
        if (!store) {
            store = {
                items: [],
                isLoading: false,
                projectModels: []
            }
        }
        return <View>
            <FlatList
                data={store.projectModels}
                renderItem={data => this.renderItem(data)}
                keyExtractor={item => "" + (item.item.id || item.item.fullName)}
                refreshControl={
                    <RefreshControl
                        title={'Loading'}
                        titleColor={THEME_COLOR}
                        colors={[THEME_COLOR]}
                        refreshing={store.isLoading}
                        onRefresh={() => this.loadData(false)}
                    />
                }
            />
            <Toast ref={'toast'} position={'center'}/>

        </View>
    }

}

const mapStateToProps = state => ({
    favorite: state.favorite,
})
const mapDispatchToProps = dispatch => ({
    onLoadFavorite: (flag, isLoading) => dispatch(actions.onLoadFavorite(flag, isLoading)),

})
// connect 只是一个function, 并不一定非要放在export后面
const FavoriteTabPage = connect(mapStateToProps, mapDispatchToProps)(FavoriteTab)

const styles = StyleSheet.create({
    welcome: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    tabStyle: {
        // width: 100,
    },
    indicatorStyle: {
        height: 2,
        backgroundColor: 'white',
    },
    labelStyle: {
        fontSize: 13,
        marginTop: 6,
        marginBottom: 6,
    },
    indicatorContainer: {
        alignItems: 'center',
    },
    indicator: {
        color: 'red',
        margin: 10,
    },
})
